/**
 *
 */
package com.dchh.android.suverynew.act;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dchh.android.suverynew.R;
import com.dchh.android.suverynew.adapter.SlideAdapter;
import com.dchh.android.suverynew.base.SBaseActivity;
import com.dchh.android.suverynew.common.ZoomImagePoup;
import com.dchh.android.suverynew.views.RadioPageView;
import com.dhcc.android.base.base.MSApplication;
import com.dhcc.android.base.common.adapter.ImageGridAdapter;
import com.dhcc.android.base.common.bean.BasicProperties;
import com.dhcc.android.base.common.bean.Config;
import com.dhcc.android.base.common.bean.File;
import com.dhcc.android.base.common.bean.ImageInfoBean;
import com.dhcc.android.base.common.bean.Item;
import com.dhcc.android.base.common.bean.KeyValueBean;
import com.dhcc.android.base.common.bean.PhotosBean;
import com.dhcc.android.base.common.view.AlertDialog;
import com.dhcc.android.base.common.view.InputPopupWindow;
import com.dhcc.android.base.db.DBManagerUtil;
import com.dhcc.android.base.gis.DataController;
import com.dhcc.android.base.gis.FactoryGPS;
import com.dhcc.android.base.utils.CommenUtil;
import com.dhcc.android.base.utils.Constants;
import com.dhcc.android.base.utils.DemandDKMapUtil;
import com.dhcc.android.base.utils.FileUtil;
import com.dhcc.android.base.utils.FormUtil;
import com.dhcc.android.base.utils.PhotoUtil;
import com.dhcc.android.base.utils.StringUtil;
import com.dhcc.android.base.utils.TakeVoiceUtil;
import com.dhcc.android.base.utils.data.UploadFinish;
import com.dhcc.android.base.utils.dataparse.ConfigParse;
import com.dhcc.android.base.utils.dataparse.PhotoParse;
import com.dhcc.android.base.utils.dataparse.ThcParse;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import srs.Geometry.Envelope;
import srs.Geometry.IEnvelope;
import srs.Layer.CommonLayer;
import srs.Rendering.CommonRenderer;
import srs.Utility.sRSException;
import srs.tools.MapControl;

/**
 * 属性填报首页
 *
 * @author pengling
 * @date 2015-5-24
 */
public class DemandMainActivity extends SBaseActivity implements DemandDKMapUtil.DemandDKMapListener,PhotoUtil.PhotoUtilListener {
    // */布局
    private View view;
    /**
     * 页面载体
     */
    public View carrierView;
    public int indexPhoto;
    public int index1;
    public boolean isTake = false;
    public String infoFileName = null;
    // */调查对象
    /**
     * 调查对象集合
     */
    public List<File> fileList = new ArrayList<File>();
    /**
     * View集合
     */
    private List<View> mViews = new ArrayList<View>();
    /**
     * 页面名称集合
     */
    private List<String> radioButtonStrList = new ArrayList<String>();
    /**
     * 地块ID
     */
    public static String DKID = "";
    /**
     * 拍照工具
     */
    public PhotoUtil photoUtil;
    /**
     * 任务名称
     */
    private String taskName = null;
    /**
     * 调查包DEMAND路径
     */
    public static String path;
    /**
     * 数据库管理工具
     */
    public static DBManagerUtil dBManagerUtil;
    /**
     * 新增表单数据内容
     */
    public Map<String, String> addMap = new HashMap<String, String>();

    public Map<String, String> addTempMap = new HashMap<String, String>();
    /**
     * 系统默认数据库
     */
    private SharedPreferences sp;
    /**
     * 调查完成的数据库路径--/SURVEY/DKIDxxxx/DATA.db
     */
    public static String surveyDKIDPath;
    /**
     * 调查完成的数据库路径--null
     */
    public static String surveyDKIDPathNoData;
    /**
     * 调查成果路径
     */
    public static String surveyPath;
    /**
     * 调查成果图片信息路径
     */
    public static String surveyPhotoPath;
    /**
     * 任务包路径
     */
    private String root;
    /** */
    private String GPS;
    /**
     * 样方总数
     */
    public final String COUNT = "COUNT";
    /**
     * 空间信息全局变量
     */
    public final static String GEO = "GEO";
    /**
     * 轨迹记录计时器
     */
    private Timer timer;
    /**
     * 设备ID
     */
    private String deviceId = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.task_demand_main);
    }

    /**
     * GPS轨迹计时器
     */
    public static GetLocationBroadcastReceiver receiver;

    /**
     * 初始化GPS轨迹计时器
     */
    private void initGPSTimer() {
        timer = new Timer();
        receiver = new GetLocationBroadcastReceiver();
        String gpsRefreahTime = sp.getString(MSApplication.GPS_REFRESH_TIME,
                "60");
        System.out.println("GPS刷新时间：" + gpsRefreahTime);
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                CommenUtil.startGPSService(DemandMainActivity.this, receiver);// 开启GPS
            }
        };
        timer.schedule(task, 0, Integer.parseInt(gpsRefreahTime) * 1000);// 这个是启动定时器，每个３０秒执行一次了
    }

    @Override
    protected void setTitle(TextView toolbar_title) {

    }

    /**
     * 初始化页面
     */
    @Override
    public void initView() {
        taskName = Constants.currentTask.getTitle();
        GPS = CommenUtil.getLatLon();
        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        deviceId = tm.getDeviceId();

        try {
            CommenUtil.getMap().RemoveLayer(Constants.COMMONLAYER);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 初始化CommonLayer
        Constants.COMMONLAYER = new CommonLayer();
        try {
            CommenUtil.getMap().AddLayer(Constants.COMMONLAYER);
        } catch (IOException e) {
            e.printStackTrace();
        }
        initGPSTimer();
        if (StringUtil.isEmpty(taskName)) {
            CommenUtil.toast("参数出现问题，请重试", this);
        } else {
            root = sp.getString(MSApplication.TASK_SAVE_PATH,
                    FileUtil.getSavePath())
                    + "/" + taskName;
            path = root + "/DEMAND/";
            // taskName = "阿克苏市";
            setTitle(taskName);
        }
        dBManagerUtil = DBManagerUtil.getInstance(path, this);
        initData();
        // initPageData();
        StringUtil.dismissDialog(Constants.DIALOG);
        Constants.DIALOG = null;
        Constants.dbManagerUtil = dBManagerUtil;
        Constants.surveyDKIDPathNoData = surveyDKIDPathNoData;
        Constants.surveyPath = surveyPath;
        Constants.surveyPhotoPath = surveyPhotoPath;
        Constants.surveyDKIDPath = surveyDKIDPath;
        Constants.DKID = DKID;
        Constants.path = path;
    }

    /**
     * 初始化数据
     */
    private void initData() {
        Config config = null;
        ConfigParse pull = new ConfigParse();
        InputStream input = null;
        try {
            input = new FileInputStream(path + "CONFIG.xml");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        config = (Config) pull.getXmlObject(input);
        DKID = Constants.select.get(config.getFeild());
        System.out.println("当前DKID-----" + DKID);
        if (StringUtil.isEmpty(DKID)) {
            CommenUtil.toast("参数出现问题，请重试", this);
        } else {
            surveyDKIDPath = root + "/SURVEY/" + DKID + "/DATA.db";
            surveyDKIDPathNoData = root + "/SURVEY/" + DKID;
            surveyPath = root + "/SURVEY/";
            surveyPhotoPath = surveyPath + "PHOTO.db";
        }
        initPhotoUtil(surveyDKIDPath);
        if (config != null) {
            fileList.clear();
            fileList = config.getFile();
            if (fileList != null && fileList.size() > 0) {
                for (int i = 0; i < fileList.size(); i++) {
                    File file = fileList.get(i);
                    radioButtonStrList.add(file.getName());
                    carrierView = getLayoutInflater().inflate(
                            R.layout.util_layout_carrier, null);
                    // carrierView.setPadding(0, 0, 0, 80);
                    LinearLayout carrier_layout = (LinearLayout) carrierView
                            .findViewById(R.id.carrier_layout);// 子页面载体，解决有多个页面的情况
                    // add 地块分割
                    BasicProperties maps = file.getMaps();
                    if (maps != null && StringUtil.isNotEmpty(maps.getTitle())) {
                        DemandDKMapUtil demandDKMapUtil = new DemandDKMapUtil(this);
                        System.out.println("DKLABELNAME：" + maps.getDklabelname());
                        demandDKMapUtil.initDKMapData(maps, carrierView, file,this);
                    }

                    // 含有缩略图，暂留白
                    BasicProperties thumbnall = file.getThumbnall();
                    if (thumbnall != null
                            && StringUtil.isNotEmpty(thumbnall.getTitle())) {
                        LinearLayout map_layout = (LinearLayout) carrierView
                                .findViewById(R.id.map_layout);
                        System.out.println("DKLABELNAME："
                                + thumbnall.getDklabelname());
                        initThumbnallData(thumbnall, map_layout);// 换载体，避免放入ScrollView
                    }

                    // 含有增加表单
                    BasicProperties add = file.getAdd();
                    if (add != null && StringUtil.isNotEmpty(add.getTitle())) {//
                        initAddData(add, carrier_layout, file);
                    }

                    // 含有子列表
                    List<Item> itemList = file.getItem();// 子页面项
                    if (itemList != null && itemList.size() > 1) {
                        View childView = initListView(carrier_layout);

                        initListData(file, childView);
                    }
                    // 含有照片表单
                    BasicProperties photo = file.getPhoto();
                    if (photo != null
                            && StringUtil.isNotEmpty(photo.getTitle())) {//
                        initPhotoData(carrier_layout, file);
                    }

                    mViews.add(carrierView);
                }

                RadioPageView pageView = new RadioPageView(view, this, null,
                        false);
                pageView.iniController(mViews, radioButtonStrList);
                if (radioButtonStrList != null && radioButtonStrList.size() > 0) {
                    pageView.setChecked(Constants.radioPageViewFlag);
                }

            }

        }
    }

    public void initPhotoUtil(String surveyDKIDPath) {
        photoUtil = new PhotoUtil(this);
        photoUtil.setFilePath(surveyDKIDPathNoData);// 设初始值
    }

    // -----------------------------------缩略图-------------------------------------

    /**
     * 初始化缩略图，待完善
     *
     * @param thumbnall
     * @param carrier_layout
     */

    public void initThumbnallData(BasicProperties thumbnall,
                                  final LinearLayout carrier_layout) {

        // 几何要素现实的图层
        Constants.COMMONLAYER.setInitInfos("TableName", Constants.geometrys,
                null, srs.Geometry.srsGeometryType.Polygon,
                Constants.displayLableNames, new Envelope(), null);
        ((CommonRenderer) Constants.COMMONLAYER.getRenderer())
                .setSymbol(Constants.SYMBOLCBJ);

        carrier_layout.setVisibility(View.VISIBLE);
        final RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) carrier_layout
                .getLayoutParams();
        lp.height = (Constants.screenHight * 2) / 5;
        lp.width = Constants.screenWidth;
        carrier_layout.setLayoutParams(lp);
        if (thumbnall.getType().equals(Constants.SELF)) {
            View childView = (View) getLayoutInflater().inflate(
                    R.layout.util_panel, null);
            final LinearLayout title_layout = (LinearLayout) childView
                    .findViewById(R.id.title_layout);

            TextView title_textview = (TextView) childView
                    .findViewById(R.id.title_textview);
            // add by pengling;给缩略图增加总样方数
            title_textview.setText(thumbnall.getTitle());
            String count = "";
            System.out.println("总数：" + Constants.select.get(COUNT));
            if (Constants.select != null && !Constants.select.isEmpty()
                    && StringUtil.isNotEmpty(Constants.select.get(COUNT))
                    && Integer.parseInt(Constants.select.get(COUNT)) > 2) {
                count = "(" + Constants.select.get(COUNT) + ")";
                title_textview.setText(thumbnall.getTitle() + count);
            }

            // 地图控件
            IEnvelope env = CommenUtil.getMap().getExtent();
            final MapControl mapControl = (MapControl) childView
                    .findViewById(R.id.mapmain);
            // 给缩略图增加缩放功能
            OnClickListener openThumbnallViewClick = new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mapControl.getVisibility() == View.GONE) {
                        lp.height = (Constants.screenHight * 2) / 5;
                        lp.width = Constants.screenWidth;
                        carrier_layout.setLayoutParams(lp);
                        mapControl.setVisibility(View.VISIBLE);
                    } else {
                        lp.height = title_layout.getHeight();
                        lp.width = Constants.screenWidth;
                        carrier_layout.setLayoutParams(lp);
                        mapControl.setVisibility(View.GONE);
                    }
                }
            };
            childView.findViewById(R.id.action_down).setOnClickListener(
                    openThumbnallViewClick);
            title_layout.setOnClickListener(openThumbnallViewClick);
            mapControl.getActiveView().FocusMap(CommenUtil.getMap());
            CommenUtil.getMap().setExtent(env);

            CommenUtil.getMap().setDeviceExtent(
                    new Envelope(0, 0, mapControl.getWidth(), mapControl
                            .getHeight()));
            // 刷新图层
            mapControl.Refresh();

            // add 杨宗仁 GPS信号显示
            TextView tv_info = (TextView) childView.findViewById(R.id.info);
            tv_info.setBackgroundColor(Color.argb(128, 255, 255, 255));
            tv_info.setTextColor(Color.BLACK);
            try {
                FactoryGPS factory = new FactoryGPS(tv_info, null, null, null,
                        mapControl);
                FactoryGPS.NaviStart = false;
                factory.StartStopGPS(this, tv_info);
            } catch (Exception e) {
                e.printStackTrace();
            }

            mapControl.Refresh();
            carrier_layout.addView(childView);
        }
    }

    // -----------------------------------列表-------------------------------------

    public View initListView(LinearLayout carrier_layout) {
        View childView = (View) getLayoutInflater().inflate(
                R.layout.util_listview, null);
        childView.findViewById(R.id.title_layout).setVisibility(View.VISIBLE);
        carrier_layout.addView(childView);
        return childView;
    }

    /**
     * 初始化列表，待保存上次数据
     *
     * @param file
     * @param carrier_layout
     */
    @SuppressWarnings("unchecked")
    public void initListData(final File file, View childView) {
        final ListView listView = (ListView) childView.findViewById(R.id.list);
        TextView title_text = (TextView) childView
                .findViewById(R.id.title_textview);
        String name = file.getName();
        if (!name.endsWith("列表")) {
            name = name + "列表";
        }
        title_text.setText(name);
        if (StringUtil.isNotEmpty(file.getTable())) {
            List<Item> itemList = file.getItem();
            final String table = file.getTable();
            final List<Map<String, String>> entityList = dBManagerUtil
                    .getListData(table, CommenUtil.itemToStrList(itemList),
                            file.getPfeild(), DKID, surveyDKIDPath);
            System.out.println("列表数：" + entityList.size());
            if (title_text.getText().toString().contains("地块")) {// 有地块二字的才显示列表数？？
                title_text.setText(name + setCountTextView(entityList.size()));
            }

            System.out.println("查出的列表：" + entityList.size() + ","
                    + file.getPfeild() + ":" + DKID);
            InputStream inputStream = null;
            if (file.getAdd() != null) {
                inputStream = CommenUtil.initStreamData(file.getProperties(),
                        path, this);
            }
            List<BasicProperties> fieldList = ThcParse.getXmlThc(inputStream);
            List<KeyValueBean> keyValueList = null;

            boolean isNoAdapter = false;
            if (listView.getAdapter() == null) {
                isNoAdapter = true;
            }
            final SlideAdapter slideAdapter = new SlideAdapter(this,
                    entityList, 0, itemList, keyValueList, title_text, name);
            listView.setAdapter(slideAdapter);
            slideAdapter.notifyDataSetChanged();
            // //设置为原大小
            StringUtil.setListViewHeightBasedOnChildren(listView);
            listView.setVerticalScrollBarEnabled(false);
            // if(isNoAdapter){
            slideAdapter.setClicklistener(new SlideAdapter.ClickListenerInterface() {
                @Override
                public void doOperate(int position) {// 删除
                    if (StringUtil.isFastDoubleClick(500)) {
                        return;
                    }
                    isAlertDown(DemandMainActivity.this, "确定要删除该记录吗？",
                            slideAdapter, "确定", "取消", position, file, listView);
                }

                @Override
                public void doItem(int position) {// 进入详情
                    if (StringUtil.isFastDoubleClick(500)) {
                        return;
                    }
                    String rowid = entityList.get(position).get("rowid");
                    goAddActivity(rowid, file);
                }
            });
            // }
            listView.setDivider(null);
        }

    }

    public static int childCount = 0;

    public String setCountTextView(int childCount) {
        this.childCount = childCount;
        String count = "";
        if (Constants.select != null && !Constants.select.isEmpty()
                && StringUtil.isNotEmpty(Constants.select.get(COUNT))
                && Integer.parseInt(Constants.select.get(COUNT)) > 2) {
            count = "(" + childCount + "/" + Constants.select.get(COUNT) + ")";
        }
        return count;
    }

    /**
     * 删除确认弹框
     *
     * @param context 上下文
     * @param str     文字
     * @param type    类型
     * @param right   右按钮
     * @param left    左按钮
     */
    public void isAlertDown(final Context context, String str,
                            final SlideAdapter slideAdapter, String right, String left,
                            final int position, final File file, final ListView listView) {
        final AlertDialog alertDialog = new AlertDialog(context, str, right,
                left);
        alertDialog.show();
        alertDialog.setClicklistener(new AlertDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                if (StringUtil.isFastDoubleClick(500)) {
                    return;
                }
                alertDialog.dismiss();
                if (slideAdapter != null) {// 删除列表的确认
                    String rowid = slideAdapter.mapList.get(position).get(
                            "rowid");
                    boolean isCopy = copyFileByisExist();
                    if (dBManagerUtil.deleteById(file.getTable(), "rowid",
                            rowid, surveyDKIDPath)) {
                        CommenUtil.toast("删除成功！", DemandMainActivity.this);
                        //
                        slideAdapter.mapList.remove(position);
                        if (slideAdapter.title_text.getText().toString()
                                .contains("地块")) {// 有地块二字的才显示列表数？？
                            slideAdapter.title_text.setText(slideAdapter.title
                                    + setCountTextView(slideAdapter.getCount()));
                        }
                        slideAdapter.notifyDataSetChanged();
                        StringUtil.setListViewHeightBasedOnChildren(listView);
                    } else {
                        if (isCopy) {// 新复制
                            FileUtil.deleteFile(surveyDKIDPathNoData);
                        }
                        CommenUtil.toast("删除失败！", DemandMainActivity.this);
                    }
                } else {// 撤销填写数据操作
                    if (voiceKey.equals(photoKey)) {// 共用一个字段
                        FormUtil.deleteNoData(oldDataMap, addMap, surveyPath,
                                photoKey);
                    } else {
                        FormUtil.deleteNoData(oldDataMap, addMap, surveyPath,
                                photoKey);
                        FormUtil.deleteNoData(oldDataMap, addMap, surveyPath,
                                voiceKey);
                    }
                    // if (oldDataMap.isEmpty()
                    // || StringUtil.isEmpty(oldDataMap.get(voiceKey))
                    // && !addMap.isEmpty()) {
                    // String voiceStr = addMap.get(voiceKey);
                    // if (StringUtil.isNotEmpty(voiceStr)
                    // && voiceStr.contains(TakeVoiceUtil.voiceName)) {
                    // FileUtil.deleteFile(TakeVoiceUtil.voicePath);//
                    // System.out.println("333deleteFile"+TakeVoiceUtil.voicePath);
                    // }
                    // }

                    TakeVoiceUtil.voicePath = "";
                    TakeVoiceUtil.oldVoicePath = "";
                    ((Activity) context).finish();
                }
            }

            @Override
            public void doCancel() {
                alertDialog.dismiss();
            }
        });
    }

    // -----------------------------------表单增加-------------------------------------

    /**
     * 新增表单面板
     *
     * @param add
     * @param carrier_layout
     */
    private void initAddData(final BasicProperties add,
                             LinearLayout carrier_layout, final File file) {
        if (add.getType().equals(Constants.SELF)) {// 在本页
            LinearLayout save_layout = (LinearLayout) carrierView
                    .findViewById(R.id.save_layout);
            save_layout.setVisibility(View.VISIBLE);
            save_layout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (StringUtil.isFastDoubleClick(500)) {
                        return;
                    }
                    int i = saveData(file, dBManagerUtil, file.getPfeild(),
                            DKID, false);
                    switch (i) {
                        case 0:// 跳出监听
                            return;
                        case 1:// 成功
                            // CommenUtil.copyFile(path + "DATA.db",
                            // surveyDKIDPath);
                            CommenUtil.toast("保存成功！", DemandMainActivity.this);
                            break;
                        case 2:// 失败
                            CommenUtil.toast("保存失败！", DemandMainActivity.this);
                            break;
                        default:
                            break;
                    }
                }
            });
            InputStream input = CommenUtil.initStreamData(file.getProperties(),
                    path, this);
            initFormView(carrier_layout, input, carrierView, file, DKID,
                    file.getPfeild(), dBManagerUtil, DKID, add.getTitle());
        } else if (add.getType().equals(Constants.NEW)) {
            OnClickListener opreateClick = new OnClickListener() {// 编辑单位区属性
                @Override
                public void onClick(View v) {
                    if (StringUtil.isFastDoubleClick(500)) {
                        return;
                    }
                    goAddActivity(null, file);
                }
            };
            Map<Integer, OnClickListener> imgMap = new HashMap<Integer, OnClickListener>();
            imgMap.put(R.mipmap.add, opreateClick);
            setImgBtnClick(carrierView, imgMap);
        }
    }

    public boolean isClickSave = false;// 是否点击保存按钮，用于编辑后的判断

    /**
     * 保存数据
     *
     * @param file          CONFIG节点名
     * @param dBManagerUtil db数据库
     * @param rowKey        字段名
     * @param rowid
     * @param isList        是否为集合
     * @return
     */
    public int saveData(File file, DBManagerUtil dBManagerUtil, String rowKey,
                        String rowid, Boolean isList) {
        boolean isSuccess = false;
        boolean isY = false;
        boolean isN = false;
        isClickSave = true;
        boolean isCopy = false;
        System.out.println("需保存的addMap:" + addMap);
        copyFileByisExistPhotos();
        if (isTake) {
            //isY = dBManagerUtil.addValues("PHOTO", photoUtil.imageGridAdapter.photosList, surveyPhotoPath);
            isY = dBManagerUtil.addValues2("PHOTO", photoUtil.imageGridAdapter.photosList, FormUtil.photoKeyList, surveyPhotoPath);
            isTake = false;
        }
        if (FormUtil.isphotoDelete) {
            isN = dBManagerUtil.deleteByKey("PHOTO", infoFileName, surveyPhotoPath);
            FormUtil.isphotoDelete = false;
        }
        if (addMap.isEmpty() || addMap.size() == 1) {
            CommenUtil.toast("数据不能全部为空", DemandMainActivity.this);
            return 0;
        } else {
            isCopy = copyFileByisExist();
            if (!oldDataMap.isEmpty()) {// 修改数据
                if (!oldDataMap.equals(addMap)) {
                    addMap.remove("rowid");
                    isSuccess = dBManagerUtil.updateById(addMap, keyList,
                            file.getTable(), rowKey, rowid, surveyDKIDPath);// 只有一行数据
                    if (isSuccess) {
                        if (!StringUtil.isEmpty(voiceKey)
                                && !TakeVoiceUtil.oldVoicePath
                                .equals(TakeVoiceUtil.voicePath)
                                && FileUtil
                                .isExistFile(TakeVoiceUtil.voicePath)) {// 有录音
                            FileUtil.deleteFile(TakeVoiceUtil.oldVoicePath);
                            // FileUtil.renameFile(TakeVoiceUtil.voicePath,
                            // TakeVoiceUtil.oldVoicePath);// 新名换成旧名
                        }
                    }

                } else {
                    isSuccess = true;
                }
            } else {// 添加数据
                if (!addMap.isEmpty()) {
                    addMap.put(file.getPfeild(), DKID);// 不知道地块编号外键是否真的可以编辑
                    addMap.remove("rowid");// 让rowid自增
                    System.out.println("addMap:" + addMap);
                    isSuccess = dBManagerUtil.add(addMap, keyList,
                            file.getTable(), "", surveyDKIDPath);

                } else {
                    isSuccess = true;
                }
            }
            if (TakeVoiceUtil.isDelete) {// 全部删除
                FileUtil.deleteFile(TakeVoiceUtil.oldVoicePath);
            }
            if (pathList != null && pathList.size() > 0) {// 删掉多余的照片
                for (String path : pathList) {
                    System.out.println("SSpathList:" + pathList);
                    photoUtil.deleteAttachmentFile(surveyPath + path);
                }
            }

        }
        /*if (isY) {
            Toast.makeText(this,"chengong", 1000).show();
		}
		if (isN) {
			Toast.makeText(this,"chengong", 1000).show();
		}*/
        if (isSuccess) {
            oldDataMap = StringUtil.setMapToMap(addMap, oldDataMap);// 给oldDataMap赋值，防止出现多次添加的情况
            if (Constants.isNetworkAvailable(this)) {
                if (isList) {
                    childCount = childCount + 1;
                } else {
                    childCount = 1;
                }
                new UploadFinish(this, Constants.currentTask.getTaskid(), DKID,
                        childCount + "");// 上传状态至服务器
            }

            return 1;
        } else {
            if (isCopy) {// 不成功，第一次创建删除文件夹
                FileUtil.deleteFile(surveyDKIDPathNoData);
            }
            return 2;
        }

    }

    public List<String> keyList;
    public boolean isFormEdit = false;// 表单框是否被编辑

    @SuppressWarnings("unchecked")
    public void initFormView(LinearLayout carrier_layout, InputStream input,
                             View carrierView, File file, Object rowValue, String rowKey,
                             DBManagerUtil dBManagerUtil, String DKID, String title) {
        List<BasicProperties> fieldList = ThcParse.getXmlThc(input);
        keyList = CommenUtil.basicPropertieToStrList(fieldList);
        keyList.add("GEO");
        BasicProperties add = file.getAdd();
        carrier_layout.findViewById(R.id.title_layout).setVisibility(
                View.VISIBLE);
        TextView title_textview = (TextView) carrier_layout
                .findViewById(R.id.title_textview);
        // String title = add.getTitle();
        oldDataMap.clear();
        addMap.clear();
        addTempMap.clear();
        if (rowValue != null) {
            List<Map<String, String>> dataMapList = dBManagerUtil.getListData(
                    file.getTable(), keyList, rowKey, rowValue, surveyDKIDPath);
            if (dataMapList != null && dataMapList.size() > 0) {
                title = title.replace("新增", "");
                oldDataMap = dataMapList.get(0);
                addMap = StringUtil.setMapToMap(oldDataMap, addMap);
                System.out.println("初始化老数据：" + oldDataMap);
            } else {
                rowValue = null;
            }
        } else {
            oldDataMap.clear();
        }
        title_textview.setText(title);
        FormUtil.fieldSet = "";
        boolean isClear = oldDataMap.isEmpty();
        boolean isEnd = false;
        if (keyList.contains("GPS")) {
            addMap.put("GPS", Constants.GPS);
        }
        oldDataMap.put(file.getPfeild(), DKID);
        addMap.put(file.getPfeild(), DKID);
        // oldDataMap.put(GEO, Constants.geometrys.toString());
        // addMap.put(GEO, Constants.geometrys.toString());
        for (BasicProperties field : fieldList) {
            // 初始化默认控制，根据继承关系来，暂且未对herit为2的情况 进行分析
            System.out.println("Inherit:" + field.getInherit() + ","
                    + field.getPfeild());
            if (StringUtil.isNotEmpty(field.getInherit())
                    && field.getInherit().equals("1")
                    && StringUtil.isNotEmpty(field.getPfeild())) {
                String pfeild = field.getPfeild();
                if (Constants.select != null && !Constants.select.isEmpty()) {
                    if (addMap.get(field.getName()) == null
                            || addMap.get(field.getName()).isEmpty()) {
                        String value = Constants.select.get(pfeild);
                        if (field.getLabel().endsWith("（亩）")) {
                            Double area = Double.parseDouble(value);
                            if (area >= 99) {
                                area = (Double) (area / 666.7);
                            }

                            DecimalFormat df = new DecimalFormat("######0.00");
                            value = df.format(area) + "";
                        }
                        oldDataMap.put(field.getName(), value);
                        addMap.put(field.getName(), value);
                    }
                }
            }
            if (fieldList.get(fieldList.size() - 1).getName()
                    .equals(field.getName())) {
                isEnd = true;// 如何检测过滤后的最后一个?
            }

            System.out.println("show:" + field.isShow() + "," + rowValue);
            if (field.isShow()) {
                initAddLayout(field, carrier_layout, isEnd, file.getPfeild(),
                        DKID, fieldList);
            }

        }
        if (isClear) {
            addTempMap = StringUtil.setMapToMap(addMap, addTempMap);
            oldDataMap.clear();
        }
    }

    public Map<String, String> oldDataMap = new HashMap<String, String>();

    /**
     * 初始化表单框
     *
     * @param field
     * @param allEntity
     * @param carrier_layout
     */
    private void initAddLayout(BasicProperties field,
                               LinearLayout carrier_layout, Boolean isEnd, String DKIDstr,
                               String DKID, List<BasicProperties> fieldList) {

        FormUtil formUtil = new FormUtil(this, field, isEnd, fieldList);
        String input = field.getInput();// 组合方式具体有哪些，不能太动态
        if (input.startsWith("0") || input.contains("|0")
                || input.startsWith("5") || input.contains("|5")
                || input.startsWith("3") || input.contains("|3")
                || input.startsWith("4") || input.contains("|4")
                || input.startsWith("6") || input.contains("|6")) {// 文本框（文字）
            if (input.startsWith("5") || input.contains("|5")) {// 选框
                // fieldset（50：单选；53：多选；）；abc（56：单选；57：多选）
                boolean isSingle = true;
                if (input.contains("53") || input.contains("57")) {// 多选
                    isSingle = false;
                }
                String beanType = Constants.SortBeanTypeByABC;
                if (input.contains("50") || input.contains("53")) {// 多选
                    beanType = Constants.SortBeanTypeByField;
                }
                int showType = 0;
                if (input.contains("501") || input.contains("531")
                        || input.contains("561") || input.contains("571")) {
                    showType = 1;
                }
                if (input.contains("502") || input.contains("532")
                        || input.contains("562") || input.contains("572")) {// 如：103
                    showType = 2;
                }
                if (input.contains("503") || input.contains("533")
                        || input.contains("563") || input.contains("573")) {// 如：水稻
                    showType = 3;
                }
                System.out.println("showType:" + showType);
                List<Item> itemList = field.getItem();
                carrier_layout.addView(formUtil.initSelectPoup(isSingle,
                        CommenUtil.itemToKeyValue(itemList, showType), null,
                        oldDataMap, beanType));
            } else {// 普通表单框
                carrier_layout.addView(formUtil.initEditText(
                        formUtil.getTextType(input), -1, null, oldDataMap));
            }

        }

        // if (input.contains("301")) {// 经纬度合并
        // carrier_layout.addView(formUtil.initEditText(
        // EditorInfo.TYPE_CLASS_TEXT, EditorInfo.IME_ACTION_NEXT,
        // "参考坐标点", oldDataMap));
        // }

        if (input.contains("201")) {// 照相
            photoKey = field.getName();
            pathList.clear();
            List<ImageInfoBean> imageInfoList = new ArrayList<ImageInfoBean>();
            if (!oldDataMap.isEmpty()) {
                String photo = oldDataMap.get(photoKey);
                pathBefore = photo;
                System.out.println("初始照片：" + pathBefore);
                if (StringUtil.isNotEmpty(photo)) {
                    String[] paths = photo.split(",");
                    for (String path : paths) {
                        if (!path.contains(".mp3")) {
                            // Bitmap bitmap = photoUtil
                            // .loadBitmapImage(surveyPath + path);
                            ImageInfoBean imageInfoBean = new ImageInfoBean(
                                    null, surveyPath + path, path);
                            imageInfoList.add(imageInfoBean);
                        }
                    }
                }
            }

            ImageGridAdapter imageGridAdapter = new ImageGridAdapter(this,
                    imageInfoList, null);

            carrier_layout.addView(formUtil.initTakePhoto(imageGridAdapter));

        }
        if (input.contains("202")) {// 录音
            voiceKey = field.getName();
            String voicePath = oldDataMap.get(voiceKey);// 原有的录音?由于录音唯一，目前根据地址直接找以前录音
            String voiceName = "";
            if (StringUtil.isNotEmpty(voicePath)) {
                String[] paths = voicePath.split(",");
                for (String path : paths) {
                    if (path.contains(".mp3")) {
                        voiceName = path.substring(path.lastIndexOf("/") + 1);
                        break;// 只有一个
                    }
                }
            }
            System.out.println("录音路径之前：" + surveyDKIDPathNoData + ",voiceName:"
                    + voiceName);
            carrier_layout.addView(formUtil.initVoice(surveyDKIDPathNoData,
                    voiceName));

        }
    }

    public String voiceKey = "";

    /**
     * 跳转去增加页面
     *
     * @param add
     */
    public void goAddActivity(String rowid, File file) {
        Intent intent = new Intent(DemandMainActivity.this,
                AddFormActivity.class);
        intent.putExtra("rowid", rowid);
        intent.putExtra("path", path);
        intent.putExtra("surveyDKIDPath", surveyDKIDPath);
        intent.putExtra("file", file);
        if (file.getAdd() != null) {
            intent.putExtra("bp", file.getAdd());
        }
        intent.putExtra(file.getPfeild(), DKID);
        startActivity(intent);
    }

    // --------------------------------拍照---------------------------
    private final static int CAMERA_RESULT = 800;

    public static String pathBefore = "";
    // private LinearLayout editLayout;
    private LinearLayout photo_layout;

    /**
     * 新增照片
     * 遥感产量调查（阿克苏市）
     *
     * @param photo
     * @param carrier_layout
     */
    private void initPhotoData(LinearLayout carrier_layout, final File file) {
        photo_layout = carrier_layout;
        final BasicProperties photo = file.getPhoto();
        InputStream input = CommenUtil.initStreamData(file.getProperties(),
                path, this);
        PhotoParse photoParse = new PhotoParse();
        photoParse.getXmlObject(input, photo);
        photoUtil.setFilePath(surveyDKIDPathNoData + "/" + photo.getDir());
        fieldList = new ArrayList<String>();
        fieldList.add(file.getPfeild());
        fieldList.add("LAT");
        fieldList.add("LON");
        fieldList.add("TIME");
        fieldList.add("NAME");
        List<ImageInfoBean> imageInfoList = new ArrayList<ImageInfoBean>();
        showPhotoData(imageInfoList, file);
        FormUtil formUtil = new FormUtil(this, null, false, null);
        final ImageGridAdapter imageGridAdapter = new ImageGridAdapter(this,
                imageInfoList, file);

        // List<Bitmap> bitmapList=new ArrayList<Bitmap>();
        initAdapterView(imageGridAdapter, file, carrierView);
        carrier_layout.addView(formUtil.initTakeGirdPhoto(imageGridAdapter,
                file));
        if (photo.isIstake()) {// 有照相
            OnClickListener opreateClick = new OnClickListener() {// 编辑单位区属性
                @Override
                public void onClick(View v) {
                    if (StringUtil.isFastDoubleClick(500)) {
                        return;
                    }
                    String path = "";

                    if (photo.getMaxsize().equals("1")) {
                        path = photo.getTitle() + ".jpg";
                    } else {
                        path = FileUtil.getPhotoFileName(".jpg");
                    }
                    path = photoUtil.getSavePath(path);
                    clickFile = file;
                    Constants.takePhotoFlag = "grid";
                    photoUtil.takePhoto(path, imageGridAdapter,DemandMainActivity.this);
                }
            };
            Map<Integer, OnClickListener> imgMap = new HashMap<Integer, OnClickListener>();
            imgMap.put(R.mipmap.camera, opreateClick);
            setImgBtnClick(carrierView, imgMap);
        }
    }

    /**
     * 展示照片数据库数据
     *
     * @param imageInfoList
     * @param file
     */
    private void showPhotoData(List<ImageInfoBean> imageInfoList, File file) {
        List<Map<String, String>> photoMap = dBManagerUtil.getListData(
                file.getTable(), fieldList, file.getPfeild(), DKID,
                surveyDKIDPath);
        if (photoMap != null && photoMap.size() > 0) {
            for (Map<String, String> map : photoMap) {
                String name = map.get("NAME");
                String fileName = "";
                if (file.getPhoto().getMaxsize().equals("1")) {
                    fileName = file.getPhoto().getTitle() + ".jpg";
                } else {
                    fileName = name;
                }

                String path = photoUtil.getSavePath(fileName);
                // Bitmap bitmap = photoUtil.loadBitmapImage(path);

                ImageInfoBean imageInfoBean = new ImageInfoBean(name.replace(
                        ".jpg", ""), path, path);
                imageInfoList.add(imageInfoBean);
            }
        }

    }

    private List<String> pathList = new ArrayList<String>();

    /**
     * 初始化照片适配器的监听
     *
     * @param imageGridAdapter
     * @param file
     * @param pId
     */
    public void initAdapterView(final ImageGridAdapter imageGridAdapter,
                                final File file, final View childView) {
        LinearLayout editLayout = (LinearLayout) childView
                .findViewById(R.id.save_layout);
        if (editLayout.getVisibility() == View.GONE
                && imageGridAdapter.imageInfoList != null
                && imageGridAdapter.imageInfoList.size() > 0) {
            if (photo_layout != null) {
                photo_layout.setPadding(0, 0, 0, 80);
            }

            final TextView save_text = (TextView) childView
                    .findViewById(R.id.save_text);
            save_text.setText("编辑");
            editLayout.setVisibility(View.VISIBLE);
            editLayout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (StringUtil.isFastDoubleClick(500)) {
                        return;
                    }
                    if (imageGridAdapter.deleteVisible) {
                        imageGridAdapter.changeDeleteVisible(false);
                        save_text.setText("编辑");
                    } else {
                        save_text.setText("取消");
                        imageGridAdapter.changeDeleteVisible(true);
                    }
                    imageGridAdapter.notifyDataSetChanged();
                }
            });
            imageGridAdapter
                    .setClicklistener(new ImageGridAdapter.ClickListenerInterface() {
                        @Override
                        public void doDelete(int position) {// 删除图片
                            if (StringUtil.isFastDoubleClick(500)) {
                                return;
                            }
                            if (file == null) {// 包含在表单内
                                System.out.println("path:"
                                        + imageGridAdapter.imageInfoList
                                        .get(position).path);
                                if (!pathBefore.contains(",")) {
                                    pathBefore = "";
                                } else {
                                    pathBefore = pathBefore.replace(
                                            imageGridAdapter.imageInfoList
                                                    .get(position).path, ",");
                                    System.out.println("1111111:" + pathBefore);
                                    pathBefore = pathBefore.replace(",,", "");
                                    System.out.println("2222222:" + pathBefore);
                                }

                                addMap.put(photoKey, pathBefore);// 多张用逗号隔开

                                pathList.add(imageGridAdapter.imageInfoList
                                        .get(position).path);
                                photoUtil
                                        .deleteAttachmentFile(imageGridAdapter.imageInfoList
                                                .get(position).path);
                                System.out.println("删掉的：" + pathList + ",剩下的："
                                        + pathBefore);
                                imageGridAdapter.photosList.clear();
                                ;
                                FormUtil.isphotoDelete = true;
                                String[] Fn = imageGridAdapter.imageInfoList.get(position).getAbsolutePath().split("/");
                                indexPhoto = imageGridAdapter.imageInfoList.get(position).getAbsolutePath().split("/").length - 1;
                                infoFileName = Fn[indexPhoto];
                                imageGridAdapter.imageInfoList.remove(position);

                                initAdapterView(imageGridAdapter, null,
                                        childView);
                                imageGridAdapter.notifyDataSetChanged();
                            } else {// 单独photo表
                                boolean isCopy = copyFileByisExist();
                                if (dBManagerUtil.deleteById(
                                        file.getTable(),
                                        file.getPhoto().getFeild(),
                                        imageGridAdapter.imageInfoList
                                                .get(position).imageMsg
                                                + ".jpg", surveyDKIDPath)) {
                                    photoUtil
                                            .deleteAttachmentFile(imageGridAdapter.imageInfoList
                                                    .get(position).path);
                                    FileUtil.copyFile(path + "DATA.db",
                                            surveyDKIDPath);
                                    CommenUtil.toast("删除成功",
                                            DemandMainActivity.this);
                                    imageGridAdapter.imageInfoList
                                            .remove(position);
                                    initAdapterView(imageGridAdapter, file,
                                            childView);
                                    imageGridAdapter.notifyDataSetChanged();
                                } else {
                                    if (isCopy) {
                                        FileUtil.deleteFile(surveyDKIDPathNoData);
                                    }
                                    CommenUtil.toast("删除失败，请重试",
                                            DemandMainActivity.this);
                                }
                            }

                        }

                        @Override
                        public void doBitmap(int position, View v) {
                            if (StringUtil.isFastDoubleClick(500)) {
                                return;
                            }
                            String path = imageGridAdapter.imageInfoList.get(
                                    position).getAbsolutePath();
                            if (StringUtil.isNotEmpty(path)) {
                                Bitmap bitmap = photoUtil.loadBitmapImage(path);
                                ZoomImagePoup poup = new ZoomImagePoup(
                                        DemandMainActivity.this);
                                poup.initPopWindow(v, bitmap);
                            }
                        }
                    });
        } else if (imageGridAdapter.imageInfoList == null
                && imageGridAdapter.imageInfoList.size() == 0) {
            editLayout.setVisibility(View.GONE);
        }
    }

    private File clickFile;// 当前点击的照片对象

    /**
     * 拍照后返回的结果
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CAMERA_RESULT) {
            if (photoUtil.getPhotoSize(photoUtil.mPhotoPath) == 0) {// 文件内容为空
                // photoUtil.releaseImage(photoUtil.mPhotoPath);
                photoUtil.deleteAttachmentFile(photoUtil.mPhotoPath);
            } else {
                if (StringUtil.isNotEmpty(Constants.takePhotoFlag)) {
                    if (Constants.takePhotoFlag.equals("grid")) {
                        doWithGridPhoto();
                    } else if (Constants.takePhotoFlag.equals("gallery")) {
                        String date = photoUtil.getCurrTime("yyyy-MM-dd");
                        String location = CommenUtil.getLatLon();// 获取当前地址经纬度
                        String lat = "", lon = "";
                        if (StringUtil.isNotEmpty(location)) {
                            lat = location.split(",")[0];
                            lon = location.split(",")[1];
                        }
                        System.out.println("======:" + photoUtil.mPhotoPath);
                        Bitmap bitmap = photoUtil.doPhoto(photoUtil.mPhotoPath,
                                "时间:" + date + "," + FormUtil.text);

                        if (bitmap != null) {
                            System.out.println("照片之前：" + pathBefore);
                            if (StringUtil.isEmpty(pathBefore)) {
                                pathBefore = photoUtil.mPhotoPath.replace(
                                        surveyPath, "");

                            } else {
                                pathBefore = pathBefore
                                        + ","
                                        + photoUtil.mPhotoPath.replace(
                                        surveyPath, "");
                            }
                            addMap.put(photoKey, pathBefore);// 多张用逗号隔开
                            ImageInfoBean imageInfoBean = new ImageInfoBean(
                                    null, photoUtil.mPhotoPath,
                                    photoUtil.mPhotoPath);
                            String[] fileNames = photoUtil.mPhotoPath.split("/");
                            PhotosBean photosBean = new PhotosBean(fileNames[fileNames.length - 1], lat, lon, date, FormUtil.photoMap);
                            photoUtil.imageGridAdapter.photosList.add(photosBean);
                            isTake = true;
                            photoUtil.imageGridAdapter.imageInfoList
                                    .add(imageInfoBean);
                            photoUtil.imageGridAdapter.notifyDataSetChanged();
                            initAdapterView(photoUtil.imageGridAdapter, null,
                                    FormUtil.photoView);
                        } else {
                            // photoUtil.releaseImage(photoUtil.mPhotoPath);
                            photoUtil
                                    .deleteAttachmentFile(photoUtil.mPhotoPath);
                        }
                        bitmap.recycle();

                    }
                }
            }

        }

    }

    /**
     * 处理后期图片
     *
     * @param bitmap
     */
    private void doWithGridPhoto() {
        InputPopupWindow poup = new InputPopupWindow(this);// ？？点击取消拍照，不弹框
        poup.showInputPoupWindow(view, null, clickFile.getPhoto().getLabels()
                .get(0).getLabel(), true, 0, false);
        poup.setClicklistener(new InputPopupWindow.ClickListenerInterface() {
            @Override
            public void doConfirm(String value) {
                if (StringUtil.isFastDoubleClick(500)) {
                    return;
                }
                String date = photoUtil.getCurrTime("yyyy-MM-dd");
                String location = CommenUtil.getLatLon();// 获取当前地址经纬度
                String lat = "", lon = "";
                if (StringUtil.isNotEmpty(location)) {
                    lat = location.split(",")[0];
                    lon = location.split(",")[1];
                }
                Bitmap bitmap = photoUtil.doPhoto(photoUtil.mPhotoPath, value
                        + "  " + date + "," + clickFile.getPfeild() + ":"
                        + DKID + "," + "经度：" + lon + "," + "纬度：" + lat);
                if (bitmap != null) {
                    copyFileByisExist();
                    if (!clickFile.getPhoto().getMaxsize().equals("1")) {// 只添加一条
                        photoUtil.renameFile(photoUtil.mPhotoPath, value);
                    } else {
                        dBManagerUtil.deleteById(clickFile.getTable(),
                                clickFile.getPfeild(), DKID, surveyDKIDPath);
                        photoUtil.renameFile(photoUtil.mPhotoPath, clickFile
                                .getPhoto().getTitle());
                        // photoUtil.releaseImage(photoUtil.oldPhotoPath);
                    }
                    dealImgToDB(date, value, lat, lon);// 存在：修改；不存在：增加
                    photoUtil.imageGridAdapter.imageInfoList.clear();
                    showPhotoData(photoUtil.imageGridAdapter.imageInfoList,
                            clickFile);
                    photoUtil.imageGridAdapter.notifyDataSetChanged();
                    initAdapterView(photoUtil.imageGridAdapter, clickFile,
                            mViews.get(Constants.radioPageViewFlag));// 给适配器加监听
                } else {
                    // photoUtil.releaseImage(photoUtil.mPhotoPath);
                    photoUtil.deleteAttachmentFile(photoUtil.mPhotoPath);
                }
            }

            @Override
            public void doCancel() {
                photoUtil.releaseImage(photoUtil.mPhotoPath);
                photoUtil.deleteAttachmentFile(photoUtil.mPhotoPath);
            }
        });

    }

    private List<String> fieldList;

    /**
     * 处理图片信息进数据库
     *
     * @param date
     * @param value
     */
    private void dealImgToDB(String date, String value, String lat, String lon) {
        Map<String, String> addMap = new HashMap<String, String>();
        addMap.put(clickFile.getPfeild(), DKID);
        addMap.put("LAT", lat);
        addMap.put("LON", lon);
        addMap.put("TIME", date);
        addMap.put("NAME", value + ".jpg");
        String key = clickFile.getPhoto().getFeild();
        String table = clickFile.getTable();
        copyFileByisExist();
        dBManagerUtil.deleteById(table, key, value + ".jpg", surveyDKIDPath);
        dBManagerUtil.add(addMap, fieldList, table, key, surveyDKIDPath);
    }

    // --------------------------------------综合处理---------------------------------

    /**
     * 显示中心操作按钮，执行相关操作
     *
     * @param imgId
     */
    public void setImgBtnClick(View carrierView,
                               Map<Integer, OnClickListener> imgMap) {
        LinearLayout opreate_layout = (LinearLayout) carrierView
                .findViewById(R.id.opreate_layout);
        opreate_layout.setVisibility(View.VISIBLE);
        Set<Integer> key = imgMap.keySet();
        for (Iterator<Integer> it = key.iterator(); it.hasNext(); ) {
            Integer imgId = (Integer) it.next();
            ImageView imageView = new ImageView(this);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.setMargins(10, 0, 0, 0);
            imageView.setLayoutParams(lp);
            imageView.setImageResource(imgId);
            imageView.setOnClickListener(imgMap.get(imgId));
            opreate_layout.addView(imageView);
        }
    }

    /**
     * 判断是否存在，若非，则复制
     */
    public boolean copyFileByisExist() {
        if (!FileUtil.isExistFile(surveyDKIDPath)) {// 新文件地址不存在
            FileUtil.copyFile(path + "DATA.db", surveyDKIDPath);
            return true;
        }
        return false;
    }

    /**
     * 判断PHOTOS.db是否存在，若非，则复制
     */
    public boolean copyFileByisExistPhotos() {
        if (!FileUtil.isExistFile(surveyPhotoPath)) {// 新文件地址不存在
            FileUtil.copyFile(path + "PHOTO.db", surveyPhotoPath);
            return true;
        }
        return false;
    }

    @Override
    public void setImageBtnClick(View layout, Map<Integer, OnClickListener> imgMap) {
        setImgBtnClick(layout, imgMap);
    }

    @Override
    public void setClickSaveFalse() {
        isClickSave = false;
    }

    /**
     * 定位信息的广播
     *
     * @author pengling
     * @date 2015-6-29
     */
    private class GetLocationBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (!intent.getAction().equals(Constants.LOCATION_ACTION))
                return;
            String LocusInfo = Constants.USERNAME + "," + taskName + ","
                    + deviceId;
            String locationInfo = intent.getStringExtra(Constants.LOCATION);
            LocusInfo = LocusInfo + "," + locationInfo + ";\r\n";
            // System.out.println("GPS获得的信息：" + LocusInfo);
            if (!LocusInfo.contains("1970-01-01")) {// 已经获取到了
                String filePath = DemandMainActivity.surveyPath
                        + "LOCUSINFO.txt";
                FileUtil.saveFile(filePath, LocusInfo);
                // FileUtil.createFile(filePath);
                // FileUtil.writeFile(filePath, LocusInfo);
            }
            if (Constants.isRegistered) {
                DemandMainActivity.this.unregisterReceiver(this);// 不需要时注销
                Constants.isRegistered = false;
            }
        }
    }

    public String photoKey = "";

    private void goBack() {
        if (StringUtil.isFastDoubleClick(500)) {
            return;
        }
        System.out.println("addMap:" + addMap);
        System.out.println("oldDataMap:" + oldDataMap);
        if (!isClickSave && !addMap.isEmpty() && !oldDataMap.equals(addMap)
                && !addTempMap.equals(addMap)) {
            isAlertDown(DemandMainActivity.this, "是否撤销此次编辑？", null, "确定", "取消",
                    0, null, null);
        } else {
            Constants.radioPageViewFlag = 0;
            /*
             * added by 李忠义 20150814 去掉前一个页面中在CommonLayer里的选中状态
			 */
            try {
                CommenUtil.getMap().getElementContainer().ClearElement();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                // 从map 中删除commonLayer
                if (Constants.COMMONLAYER.getName() != null) {
                    CommenUtil.getMap().RemoveLayer(Constants.COMMONLAYER);
                }
                // if (Constants.geometrys != null) {
                // Constants.geometrys.clear();
                // }

            } catch (sRSException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            /*
             * add 杨宗仁 调用方法，判断地块是否已调查
			 */
            if (surveyDKIDPathNoData != null) {
                java.io.File file = new java.io.File(surveyDKIDPathNoData);
                if (file.exists()) {

                    DataController.getInstance().isComplete(DKID);
                }
            }

            finish();
            overridePendingTransition(R.anim.push_left_in,
                    R.anim.push_right_out);
        }

    }

    OnClickListener backListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            goBack();
        }
    };

    @Override
    protected void onDestroy() {
        if (StringUtil.isNotEmpty(TakeVoiceUtil.voicePath)
                && !TakeVoiceUtil.voicePath.equals(TakeVoiceUtil.oldVoicePath)
                && FileUtil.isExistFile(TakeVoiceUtil.voicePath)) {
            FileUtil.deleteFile(TakeVoiceUtil.oldVoicePath);// 保存新的删掉旧的
        }
        if (TakeVoiceUtil.myToastUtil != null) {
            TakeVoiceUtil.myToastUtil.stopToast();
        }
        if (photoUtil != null) {
            photoUtil.releaseImage();
        }
        new MSApplication().deleteActivity(this);
        if (timer != null) {
            timer.cancel();
            try {
                if (Constants.isRegistered) {
                    DemandMainActivity.this.unregisterReceiver(receiver);// 不需要时注销
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (TakeVoiceUtil.mediaRecorder != null && TakeVoiceUtil.isruning) {
            TakeVoiceUtil.mediaRecorder.stop(); // 停止录音
            TakeVoiceUtil.mediaRecorder.release(); // 释放资源
        }
        if (photoUtil != null && photoUtil.imageGridAdapter != null) {
            photoUtil.imageGridAdapter.releaseBitmap();// 销毁对象
        }
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            goBack();
        }
        return true;
    }

}